package com.example.jbmsuppliers.sinopec.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.ScrollView;

/**
 * @ScrollView
 * @张利国
 * @2015-5-12下午3:53:10
 */
public class MyScrollView extends ScrollView {
	private Bitmap bitmap;
	private boolean isCalled;
	private Callback mCallback;
	private View inner;
	private Rect normal = new Rect();
	private boolean animationFinish = true;
	// 滑动距离及坐标
	private float xDistance, yDistance, xLast, yLast;

	/**
	 * 包含的View
	 */
	private View mView;
	/**
	 * 存储正常时的位置
	 */
	private Rect mRect = new Rect();

	/**
	 * y坐标
	 */
	private int y;

	private boolean isFirst = true;

	public MyScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mGestureDetector = new GestureDetector(getContext(),
				new YScrollDetector());
		setFadingEdgeLength(0);

		// bitmap = ((BitmapDrawable)
		// context.getResources().getDrawable(R.drawable.ic_scroll_logo)).getBitmap();
	}

	/***
	 * 根据 XML 生成视图工作完成.该函数在生成视图的最后调用，在所有子视图添加完之后. 即使子类覆盖了 onFinishInflate
	 * 方法，也应该调用父类的方法，使该方法得以执行.
	 */
	@Override
	protected void onFinishInflate() {
		if (getChildCount() > 0) {
			mView = getChildAt(0);
		}
		super.onFinishInflate();
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (inner == null) {
			return super.onTouchEvent(ev);
		} else {
			commOnTouchEvent(ev);
		}
		return super.onTouchEvent(ev);
	}

	public void commOnTouchEvent(MotionEvent ev) {
		if (animationFinish) {
			int action = ev.getAction();
			switch (action) {
			case MotionEvent.ACTION_DOWN:
				// MyLog.i("ACTION_DOWN");
				y = (int) ev.getY();
				super.onTouchEvent(ev);
				break;
			case MotionEvent.ACTION_UP:
				// MyLog.i("ACTION_UP");
				y = 0;
				if (isNeedAnimation()) {
					animation();
				}
				super.onTouchEvent(ev);
				break;
			case MotionEvent.ACTION_MOVE:
				// MyLog.i("ACTION_MOVE");
				final float preY = y == 0 ? ev.getY() : y;
				float nowY = ev.getY();
				int deltaY = (int) (preY - nowY);
				// 滚动
				// scrollBy(0, deltaY);

				y = (int) nowY;
				// 当滚动到最上或者最下时就不会再滚动，这时移动布局
				if (isNeedMove()) {
					if (normal.isEmpty()) {
						// 保存正常的布局位置
						normal.set(inner.getLeft(), inner.getTop(),
								inner.getRight(), inner.getBottom());
					}
					// 移动布局
					inner.layout(inner.getLeft(), inner.getTop() - deltaY / 2,
							inner.getRight(), inner.getBottom() - deltaY / 2);
				} else {
					super.onTouchEvent(ev);
				}
				break;
			default:
				break;
			}
		}
	}

	private void commonOnTouch(MotionEvent ev) {
		int action = ev.getAction();
		int cy = (int) ev.getY();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			break;
		/**
		 * 跟随手指移动
		 */
		case MotionEvent.ACTION_MOVE:
			// delta = ev.getY();
			int dy = cy - y;
			if (isFirst) {
				dy = 0;
				isFirst = false;
			}
			y = cy;

			if (isNeedMove()) {
				if (mRect.isEmpty()) {
					/**
					 * 记录移动前的位置
					 */
					mRect.set(mView.getLeft(), mView.getTop(),
							mView.getRight(), mView.getBottom());
				}

				mView.layout(mView.getLeft(), mView.getTop() + dy / 3,
						mView.getRight(), mView.getBottom() + dy / 3);

				if (shouldCallBack(dy)) {
					if (mCallback != null) {
						if (!isCalled) {
							isCalled = true;
							resetPosition();
							mCallback.callback();

						}
					}
				}
			}

			break;
		/**
		 * 反弹回去
		 */
		case MotionEvent.ACTION_UP:
			if (!mRect.isEmpty()) {
				resetPosition();
			}
			break;

		}
	}

	// 是否需要开启动画
	public boolean isNeedAnimation() {
		return !normal.isEmpty();
	}

	// 开启动画移动

	public void animation() {
		// 开启移动动画
		TranslateAnimation ta = new TranslateAnimation(0, 0, 0, normal.top
				- inner.getTop());
		ta.setDuration(200);
		ta.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
				animationFinish = false;

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				inner.clearAnimation();
				// 设置回到正常的布局位置
				inner.layout(normal.left, normal.top, normal.right,
						normal.bottom);
				normal.setEmpty();
				animationFinish = true;
			}
		});
		inner.startAnimation(ta);
	}

	/**
	 * 当从上往下，移动距离达到一半时，回调接口
	 * 
	 * @return
	 */
	private boolean shouldCallBack(int dy) {

		if (dy > 0 && mView.getTop() > getHeight() / 2)
			return true;
		return false;
	}

	private void resetPosition() {
		Animation animation = new TranslateAnimation(0, 0, mView.getTop(),
				mRect.top);
		animation.setDuration(200);
		animation.setFillAfter(true);
		mView.startAnimation(animation);
		mView.layout(mRect.left, mRect.top, mRect.right, mRect.bottom);
		mRect.setEmpty();
		isFirst = true;
		isCalled = false;
	}

	/***
	 * 是否需要移动布局 inner.getMeasuredHeight():获取的是控件的总高度
	 * 
	 * getHeight()：获取的是屏幕的高度 两种情况 1中是没背景的 只需要满足是否在顶部或者底部即可 如果有背景的
	 * 还要看是否满足当前mView滚动的距离是否在最大距离scrollVIewY之内
	 * 
	 * @return
	 */
	public boolean isNeedMove() {
		int scrollY = getScrollY();
		int scrollViewY = mView.getTop();
		int offset = mView.getMeasuredHeight() - getHeight();
		if (scrollY == 0 || scrollY == offset) {
			if (hasBgIcon) {
				if (scrollViewY > this.scrollViewY) {
					return false;
				}
			}
			return true;
		}
		return false;
	}

	public void setCallBack(Callback callback) {
		mCallback = callback;
	}

	interface Callback {
		void callback();
	}

	private Bitmap bgIcon;// 下拉后出现的背景图片icon
	private int scrollViewY;// 控件下拉的最大距离
	private boolean hasBgIcon; // 是否存在背景icon，有的话需要控制下拉的最大高度

	/**
	 * 设置scrollView顶部的背景
	 * 
	 * @param drawableIcon
	 */
	public void setBackgroudIcon(Drawable drawableIcon) {
		bgIcon = ((BitmapDrawable) drawableIcon).getBitmap();
		hasBgIcon = true;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if (bgIcon != null) {
			scrollViewY = getHeight() / 4;
			int scrollY = getScrollY();
			canvas.drawBitmap(bgIcon, (getWidth() - bgIcon.getWidth()) / 2,
					(scrollViewY - bgIcon.getHeight()) / 2 + scrollY, null);
		}
		super.onDraw(canvas);
	}

	private GestureDetector mGestureDetector;

	private class YScrollDetector extends SimpleOnGestureListener {

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {

			if (Math.abs(distanceY) >= Math.abs(distanceX)) {
				return true;
			}
			return false;
		}
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			xDistance = yDistance = 0f;
			xLast = ev.getX();
			yLast = ev.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			final float curX = ev.getX();
			final float curY = ev.getY();

			xDistance += Math.abs(curX - xLast);
			yDistance += Math.abs(curY - yLast);
			xLast = curX;
			yLast = curY;

			if (xDistance > yDistance) {
				return false;
			}
		}

		return super.onInterceptTouchEvent(ev);

	}

	@Override
	public void fling(int velocityY) {
		super.fling(velocityY * 1);
	}
}